﻿using System;
using System.Web.UI.WebControls;
using SocialFront.Entities;
using SocialFront.Providers.Member;
using umbApi = umbraco;

namespace SocialFront.Web.usercontrols.Membership
{
    public partial class MembershipSignUp : System.Web.UI.UserControl
    {
        protected void Page_Init(object sender, EventArgs e)
        {
            ((umbApi.UmbracoDefault)this.Page).ValidateRequest = false;
        }
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                DOBDay.Items.Add(new ListItem("Day", "."));
                for (int i = 1; i <= 31; i++)
                {
                    DOBDay.Items.Add(new ListItem(i.ToString(), i.ToString()));
                }
                DOBmonth.Items.Add(new ListItem("Month", "."));
                for (int i = 1; i <= 12; i++)
                {
                    DOBmonth.Items.Add(new ListItem(i.ToString(), i.ToString()));
                }
                DOBYear.Items.Add(new ListItem("Year", "."));
                for (int i = (DateTime.Now.Year - 16); i >= 1900; i--)
                {
                    DOBYear.Items.Add(new ListItem(i.ToString(), i.ToString()));
                }
            }
        }

        protected void Signup_Click(object sender, EventArgs e)
        {
            if (IsPostBack && Page.IsValid)
            {
                if (MemberProvider.Provider.GetMemberFromEmail(Email.Text) == null)
                {
                    DateTime userDob;
                    string dobDate = DOBDay.SelectedValue + "/" + DOBmonth.SelectedValue + "/" +
                                     DOBYear.SelectedValue;

                    if (DateTime.TryParse(dobDate, out userDob))
                    {
                        Member member = new Member();

                        member.LoginName = Username.Text;
                        member.Password = Password.Text;
                        member.Email = Email.Text;
                        member.DateOfBirth = userDob;
                        member.Newsletter = Newsletter.Checked;

                        Member sfMember = MemberProvider.Provider.Create(member);

                        if (sfMember != null)
                        {
                            string memberUrl = BusinessLogic.BusinessLogic.CreateMemberSpace(sfMember);

                            if (!string.IsNullOrEmpty(memberUrl))
                            {
                                Response.Redirect(memberUrl);
                            }
                        }

                    }
                }
            }
        }
    }
}